package com.ukao.steward.ui.logistics.EnterFactory;


import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.annotation.NonNull;
import android.support.v4.app.Fragment;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;

import com.ukao.steward.R;
import com.ukao.steward.adapter.FactortTabFragmentAdapter;
import com.ukao.steward.base.BaseFragment;
import com.ukao.steward.bean.LogisticsCountBean;
import com.ukao.steward.bean.ScanCodeBean;
import com.ukao.steward.consts.Constant;
import com.ukao.steward.consts.SaveParams;
import com.ukao.steward.dialog.UnTakeDialogFragment;
import com.ukao.steward.eventbus.BatchEvent;
import com.ukao.steward.listener.DialogSubmitListener;
import com.ukao.steward.listener.MyOnPageChangeListener;
import com.ukao.steward.retrofit.ApiCallback;
import com.ukao.steward.ui.logistics.LeverFactory.LeverFactoryFragment;
import com.ukao.steward.ui.logistics.LeverFactory.SureBatchActivity;
import com.ukao.steward.util.CheckUtils;
import com.ukao.steward.util.L;
import com.ukao.steward.util.T;
import com.ukao.steward.widget.QMUITabSegment;
import com.ukao.steward.widget.StateButton;

import org.greenrobot.eventbus.Subscribe;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import butterknife.Unbinder;
import me.yokeyword.fragmentation.SupportFragment;
import rx.Observable;

import static com.ukao.steward.R.id.scan_btn;
import static com.ukao.steward.R.id.sure_btn;

/**
 * A simple {@link Fragment} subclass.
 * Use the {@link EnterFactoryTabFragment#newInstance} factory method to
 * create an instance of this fragment.
 */
public class EnterFactoryTabFragment extends BaseFragment {


    @BindView(R.id.back_btn)
    ImageView backBtn;
    @BindView(R.id.title)
    TextView title;
    @BindView(R.id.title_layout)
    RelativeLayout titleLayout;
    @BindView(R.id.back)
    ImageView back;
    @BindView(R.id.tabSegment)
    QMUITabSegment mTabSegment;
    @BindView(R.id.view_pager)
    ViewPager mViewPager;
    @BindView(scan_btn)
    ImageView scanBtn;
    @BindView(sure_btn)
    StateButton sureBtn;
    // TODO: Rename and change types of parameters
    private int enterType;
    boolean isload;
    private List<SupportFragment> mFragmentData;
    private LogisticsCountBean mHomeCountBean;
    private Unbinder unbinder;


    public static EnterFactoryTabFragment newInstance(int enterType, Parcelable param2) {
        EnterFactoryTabFragment fragment = new EnterFactoryTabFragment();
        Bundle args = new Bundle();
        args.putInt(ARG_PARAM1, enterType);
        args.putParcelable(ARG_PARAM2, param2);
        fragment.setArguments(args);
        return fragment;
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (getArguments() != null) {
            enterType = getArguments().getInt(ARG_PARAM1);
            mHomeCountBean = getArguments().getParcelable(ARG_PARAM2);

        }
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        View view = inflater.inflate(R.layout.fragment_enter_factory, container, false);
        unbinder = ButterKnife.bind(this, view);
        initView();
        initListener();
        return view;
    }

    @Override
    public void onSupportVisible() {
        super.onSupportVisible();
        setStatusBarTintColor(R.color.colorPrimary);
        if (isload) {
            batchCount();
        }

    }

    @Override
    public void onSupportInvisible() {
        super.onSupportInvisible();
        isload = true;

    }

    @Override
    protected void initView() {
        titleLayout.setBackgroundColor(getColors(R.color.colorPrimary));
        scanBtn.setVisibility(View.VISIBLE);
        mFragmentData = new ArrayList<>();
        mTabSegment.setDefaultNormalColor(getColors(R.color.black));
        mTabSegment.setDefaultSelectedColor(resources.getColor(R.color.blue));
        switch (enterType) {
            case 1: /*进厂*/
                title.setText("入厂袋号");
                mFragmentData.add(EnterFactoryFragment.newInstance(1, ""));
                mFragmentData.add(EnterFactoryFragment.newInstance(2, ""));
                mTabSegment.addTab(!CheckUtils.isNull(mHomeCountBean) ? new QMUITabSegment.Tab(getTextmMsgCount("未送厂", mHomeCountBean.getInSendingCnt())) : new QMUITabSegment.Tab("未送厂"));
                mTabSegment.addTab(new QMUITabSegment.Tab("已到厂"));

                break;

            case 3: /*进厂订单*/
                scanBtn.setVisibility(View.GONE);
                sureBtn.setVisibility(View.VISIBLE);
                title.setText("进厂订单");
                mFragmentData.add(ScanCodeFragment.newInstance(true, ""));
                mFragmentData.add(EnterFactoryFragment.newInstance(3, ""));
                mFragmentData.add(EnterFactoryFragment.newInstance(4, ""));
                mTabSegment.addTab(new QMUITabSegment.Tab("扫码"));
                mTabSegment.addTab(!CheckUtils.isNull(mHomeCountBean) ? new QMUITabSegment.Tab(getTextmMsgCount("未送厂", mHomeCountBean.getOrderInCnt())) : new QMUITabSegment.Tab("未送厂"));
                mTabSegment.addTab(new QMUITabSegment.Tab("已到厂"));
                break;

            case 2: /*出厂*/
                title.setText("出厂批次");
                mFragmentData.add(LeverFactoryFragment.newInstance(1, ""));
                mFragmentData.add(LeverFactoryFragment.newInstance(2, ""));
                mTabSegment.addTab(!CheckUtils.isNull(mHomeCountBean) ? new QMUITabSegment.Tab(getTextmMsgCount("未送店", mHomeCountBean.getOutSendingCnt())) : new QMUITabSegment.Tab("未送店"));
                mTabSegment.addTab(new QMUITabSegment.Tab("已到店"));
                break;

            case 4: /*出厂订单*/
                scanBtn.setVisibility(View.GONE);
                sureBtn.setVisibility(View.VISIBLE);
                title.setText("出厂订单");
                mFragmentData.add(ScanCodeFragment.newInstance(false, ""));
                mFragmentData.add(LeverFactoryFragment.newInstance(3, ""));
                mFragmentData.add(LeverFactoryFragment.newInstance(4, ""));
                mTabSegment.addTab(new QMUITabSegment.Tab("扫码"));
                mTabSegment.addTab(!CheckUtils.isNull(mHomeCountBean) ? new QMUITabSegment.Tab(getTextmMsgCount("未送店", mHomeCountBean.getOrderOutCnt())) : new QMUITabSegment.Tab("未送店"));
                mTabSegment.addTab(new QMUITabSegment.Tab("已到店"));
                break;


        }


        mViewPager.setAdapter(new FactortTabFragmentAdapter(getChildFragmentManager(), mFragmentData));
        mViewPager.setOffscreenPageLimit(mFragmentData.size() - 1);
        mTabSegment.setupWithViewPager(mViewPager, false);

    }

    @Override
    protected void initListener() {
        super.initListener();
        mViewPager.addOnPageChangeListener(new MyOnPageChangeListener() {

            @Override
            public void onPageSelected(int position) {
                super.onPageSelected(position);
                if (enterType==3||enterType==4){
                    sureBtn.setVisibility(position==0?View.VISIBLE:View.GONE);
                }

            }
        });
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        unbinder.unbind();
    }

    @OnClick({scan_btn, R.id.back_btn, sure_btn})
    public void onViewClicked(View view) {
        switch (view.getId()) {
            case scan_btn:
                String mDialogTitle = "";
                String mEditHint = "";
                switch (enterType) {
                    case 1:
                        mDialogTitle = "入厂袋号";

                        break;
                    case 2:
                        mDialogTitle = "出厂批次";
                        break;
                    case 3:
                        mDialogTitle = "进厂订单";
                        mEditHint = "请扫码或输入单号、运单号";
                        break;
                    case 4:
                        mDialogTitle = "出厂订单";

                        break;
                }

                UnTakeDialogFragment.createBuilder(getChildFragmentManager())
                        .setmTitle(mDialogTitle)
                        .setmEditHint(mEditHint)
                        .setListener(mDialogSubmitListener).show();

                break;
            case R.id.back_btn:
                finish();
                break;

            case sure_btn:
                try {
                    if (mFragmentData.size()>2){
                        ScanCodeFragment  mScanCodeFragment= (ScanCodeFragment) mFragmentData.get(0);
                        mScanCodeFragment.deleteByOprType();
                    }
                }catch (Exception  e){

                }

                break;


        }
    }

    private DialogSubmitListener mDialogSubmitListener = (DialogSubmitListener) (parent, message) -> {
        String context = (String) message;
        scanCode(context);
    };

    @Override
    protected boolean useEventBus() {
        return true;
    }

    @Subscribe
    public void onEvent(BatchEvent event) {
        switch (event.getMessage()) {
            case Msgcount:/*当接收到推送消息的时候就更新界面*/
                batchCount();
                break;
        }
    }

    /**
     * 首页 消息
     */
    public void batchCount() {
        HashMap mHashMap = new HashMap<String, String>();
        mHashMap.put("accessToken", SaveParams.getToken());
        addSubscription(apiStores().batchCount(Constant.createParameter(mHashMap)),
                new ApiCallback<LogisticsCountBean>() {
                    @Override
                    public void onSuccess(LogisticsCountBean mBean) {
                        if (mBean.getHttpCode() == 200) {
                            LogisticsCountBean mCountBean = mBean.getData();
                            switch (enterType) {
                                case 1: /*入厂*/
                                    mTabSegment.updateTabText(0, getTextmMsgCount("未送厂", mCountBean.getInSendingCnt()));
                                    break;
                                case 2: /*出厂*/
                                    mTabSegment.updateTabText(0, getTextmMsgCount("未送店", mCountBean.getOutSendingCnt()));

                                    break;
                                case 3: /*入厂订单*/
                                    mTabSegment.updateTabText(1, getTextmMsgCount("未送厂", mCountBean.getOrderInCnt()));

                                    break;

                            }
                            mTabSegment.notifyDataChanged();
                        }

                    }

                    @Override
                    public void onFinish() {


                    }
                });
    }


    /**
     * 入厂 未取
     *
     * @param msgCount
     */
    public void updataEnterNotTake(int msgCount) {
        mTabSegment.updateTabText(0, getTextmMsgCount("未送厂", msgCount));
        mTabSegment.notifyDataChanged();
    }


    /**
     * 入厂 订单
     *
     * @param msgCount
     */
    public void updataEnterOrder(int msgCount) {
        mTabSegment.updateTabText(1, getTextmMsgCount("未送厂", msgCount));
        mTabSegment.notifyDataChanged();
    }


    /**
     * 出厂 未送店
     *
     * @param msgCount
     */
    public void updataSendStore(int msgCount) {

        mTabSegment.updateTabText(enterType == 4 ? 1 : 0, getTextmMsgCount("未送店", msgCount));
        mTabSegment.notifyDataChanged();
    }


    @NonNull
    private String getTextmMsgCount(String title, int count) {
        if (count == 0) {
            return title;
        }
        return title + "(" + count + ")";
    }


    /**
     * 扫码请求
     *
     * @param result
     */
    public void scanCode(String result) {
        showProgressDialog();
        Observable observable = null;
        HashMap mHashMap = new HashMap<String, String>();
        if (enterType == 4 || enterType == 3) {
            mHashMap.put("orderNo", result);
        } else {
            mHashMap.put("code", result);
        }
        mHashMap.put("accessToken", SaveParams.getToken());
        switch (enterType) {
            case 1:
                observable = apiStores().scanCode(Constant.createParameter(mHashMap));/*入厂   扫码*/
                break;
            case 2:
                observable = apiStores().batchOutscanCode(Constant.createParameter(mHashMap));/*出厂袋号 扫码*/
                break;
            case 3:
                observable = apiStores().factoryInScanCode(Constant.createParameter(mHashMap));/*进厂订单 扫码*/
                break;
            case 4:
                observable = apiStores().OutOrdidsCanCode(Constant.createParameter(mHashMap));/*出厂订单 扫码*/
                break;

        }
        addSubscription(observable,
                new ApiCallback<ScanCodeBean>() {
                    @Override
                    public void onSuccess(ScanCodeBean model) {

                        if (model.getHttpCode() == 200) {
                            L.i("ScanCodeBean=" + model.getData().toString());
                            Intent mIntent = new Intent(_mActivity, SureBatchActivity.class);
                            Bundle bundle = new Bundle();
                            bundle.putInt(Constant.ARG_PARAM2, enterType);
                            bundle.putParcelable(Constant.ARG_PARAM1, model.getData());
                            mIntent.putExtras(bundle);
                            startActivity(mIntent);


                        } else {
                            T.show(model.getMsg());
                        }
                    }


                    @Override
                    public void onFinish() {
                        dismissProgressDialog();
                    }
                });
    }


}
